// post_list.js

import React from 'react';
import { Link } from 'react-router-dom';
import PostsView from './posts_view';
import PostEditor from './post_editor';
import { get, post } from '../utils/request';
import url from '../utils/url';
import './post_list.css';

class PostList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            posts: {},
            newPost: false
        };
        this.handleCancel = this.handleCancel.bind(this);
        this.handleSave = this.handleSave.bind(this);
        this.handleNewPost = this.handleNewPost.bind(this);
        this.refreshPostList = this.refreshPostList.bind(this);
    }

    componentDidMount() {
        this.refreshPostList();
    }

    refreshPostList() {
        get(url.getPostList()).then(data => {
            if (!data.error) {
                this.setState({
                    posts: data,
                    newPost: false
                });
            }
        });
    }

    handleSave(data) {
        const postData = {
            ...data,
            author_name: this.props.userName,
            author_id: this.props.userId,
        };
        post(url.createPost(), postData).then(data => {
            if (!data.error) {
                this.refreshPostList();
            }
        });
    }

    handleCancel() {
        this.setState({
            newPost: false
        });
    }

    handleNewPost() {
        this.setState({
            newPost: true
        });
    }

    render() {
        const { userId } = this.props;
        return (
            <div className='postList'>
                <div>
                    <h2>Post list</h2>
                    {/** only show 'create-new-post' button when user logged in */}
                    {userId != null ? <button onClick={this.handleNewPost}>New post</button> : null}
                </div>
                {this.state.newPost ? (
                    <PostEditor onSave={this.handleSave} onCancel={this.handleCancel} />
                ) : null}
                <PostsView posts={this.state.posts} />
            </div>
        );
    }
}

export default PostList;
